package com.chap10;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * <code>DelayQueueExample</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-03-30 15:10
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class DelayQueueExample {
    public static void main(String[] args) throws InterruptedException {
        DelayQueue<Order> delayQueue = new DelayQueue<>();
        delayQueue.put(new Order("order1",System.currentTimeMillis(),5000));
        delayQueue.put(new Order("order2",System.currentTimeMillis(),2000));
        delayQueue.put(new Order("order3",System.currentTimeMillis(),3000));

        while(!delayQueue.isEmpty()){
            Order take = delayQueue.take();
            System.out.println("处理订单："+take.getOrderId());
        }
    }

    static class Order implements Delayed{
        private String orderId;
        private long createTime;
        private long delayTime;

        public Order(String orderId, long createTime, long delayTime) {
            this.orderId = orderId;
            this.createTime = createTime;
            this.delayTime = delayTime;
        }

        public String getOrderId() {
            return orderId;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            long diff = createTime+delayTime-System.currentTimeMillis();
            //diff的单位是毫秒，转换为TimeUnit的单位
            return unit.convert(diff,TimeUnit.MILLISECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            long diff = this.getDelay(TimeUnit.MILLISECONDS)-o.getDelay(TimeUnit.MILLISECONDS);
            return Long.compare(diff,0);
        }
    }

}
